<template>
  <div class="admin-users">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3">用户管理</span>
      </template>
    </el-page-header>

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="总用户数" :value="statistics.total || 0">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="活跃用户" :value="statistics.active || 0">
            <template #prefix>
              <el-icon><CircleCheck /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="最近30天新增" :value="statistics.recent || 0">
            <template #prefix>
              <el-icon><UserFilled /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="最近30天活跃" :value="statistics.active_recent || 0">
            <template #prefix>
              <el-icon><Promotion /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <el-card class="action-bar" style="margin-top: 20px;">
      <el-row :gutter="20" align="middle">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名、邮箱、手机号..."
            style="width: 100%; max-width: 500px;"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-checkbox v-model="activeOnly" @change="handleFilterChange">
            仅显示活跃用户
          </el-checkbox>
          <el-button type="info" :icon="Refresh" @click="fetchUsers" style="margin-left: 10px;">
            刷新
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 用户表格 -->
    <el-card style="margin-top: 20px;">
      <el-table
        v-loading="loading"
        :data="users"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="统计信息" width="200">
          <template #default="scope">
            <div style="font-size: 12px;">
              <div>动态: {{ scope.row.posts_count || 0 }}</div>
              <div>评论: {{ scope.row.comments_count || 0 }}</div>
              <div>路线: {{ scope.row.routes_count || 0 }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="date_joined" label="注册时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.date_joined) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              :type="scope.row.is_active ? 'warning' : 'success'"
              size="small"
              @click="toggleUserActive(scope.row)"
              :loading="scope.row.updating"
            >
              {{ scope.row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteUser(scope.row)"
              :disabled="scope.row.is_superuser"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  User,
  CircleCheck,
  UserFilled,
  Promotion
} from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import logger from '../utils/logger'

export default {
  name: 'AdminUsers',
  components: {
    Search,
    User,
    CircleCheck,
    UserFilled,
    Promotion
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const users = ref([])
    const searchKeyword = ref('')
    const activeOnly = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const statistics = ref({
      total: 0,
      active: 0,
      recent: 0,
      active_recent: 0
    })

    const isAdmin = computed(() => store.getters.isAdmin)

    const fetchUsers = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          page_size: pageSize.value
        }

        if (searchKeyword.value) {
          params.search = searchKeyword.value
        }

        if (activeOnly.value) {
          params.active_only = 'true'
        }

        const data = await TravelAPI.getAdminUsers(params)
        
        if (Array.isArray(data)) {
          users.value = data.map(user => ({ ...user, updating: false }))
          total.value = data.length
        } else {
          users.value = (data.results || []).map(user => ({ ...user, updating: false }))
          total.value = data.count || 0
        }
      } catch (error) {
        logger.error('获取用户列表失败:', error)
        let errorMessage = '获取用户列表失败'
        if (error.response) {
          const status = error.response.status
          if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限访问用户列表'
          } else if (status === 500) {
            errorMessage = '服务器错误，请稍后重试'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          if (error.message.includes('timeout') || error.message.includes('Network Error')) {
            errorMessage = '网络错误，请检查网络连接'
          }
        }
        ElMessage.error(errorMessage)
      } finally {
        loading.value = false
      }
    }

    const fetchStatistics = async () => {
      try {
        const data = await TravelAPI.getUserStatistics()
        statistics.value = data
      } catch (error) {
        logger.error('获取统计数据失败:', error)
        // 统计数据获取失败不显示错误提示，避免影响用户体验
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      fetchUsers()
    }

    const handleFilterChange = () => {
      currentPage.value = 1
      fetchUsers()
    }

    const handleSizeChange = () => {
      fetchUsers()
    }

    const handleCurrentChange = () => {
      fetchUsers()
    }

    const toggleUserActive = async (user) => {
      user.updating = true
      try {
        const response = await TravelAPI.toggleUserActive(user.id)
        user.is_active = response.is_active
        ElMessage.success(response.message)
        fetchStatistics()
      } catch (error) {
        logger.error('切换用户状态失败:', error)
        ElMessage.error(error.response?.data?.error || '操作失败')
      } finally {
        user.updating = false
      }
    }

    const deleteUser = async (user) => {
      if (user.is_superuser) {
        ElMessage.warning('不能删除超级管理员')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除用户"${user.username}"吗？此操作将禁用该用户账户！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await TravelAPI.deleteAdminUser(user.id)
        ElMessage.success('用户已禁用')
        fetchUsers()
        fetchStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          logger.error('删除用户失败:', error)
          ElMessage.error(error.response?.data?.error || '删除失败')
        }
      }
    }

    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    }

    const goBack = () => {
      router.push('/admin')
    }

    onMounted(() => {
      if (!isAdmin.value) {
        ElMessage.error('您没有管理员权限')
        router.push('/')
        return
      }
      fetchUsers()
      fetchStatistics()
    })

    return {
      loading,
      users,
      searchKeyword,
      activeOnly,
      currentPage,
      pageSize,
      total,
      statistics,
      isAdmin,
      handleSearch,
      handleFilterChange,
      handleSizeChange,
      handleCurrentChange,
      toggleUserActive,
      deleteUser,
      fetchUsers,
      formatDate,
      goBack,
      Search,
      Refresh,
      User,
      CircleCheck,
      UserFilled,
      Promotion
    }
  }
}
</script>

<style scoped>
.admin-users {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
}

.admin-users :deep(.el-card) {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.admin-users :deep(.el-card:hover) {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.admin-users :deep(.el-statistic) {
  text-align: center;
}

.admin-users :deep(.el-statistic__head) {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.admin-users :deep(.el-statistic__number) {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.action-bar {
  margin-bottom: 20px;
}

.admin-users :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.admin-users :deep(.el-table th) {
  /* 南昌红到滕王阁金渐变 */
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  color: white;
  font-weight: 600;
}

.admin-users :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f8f9fa;
}

.admin-users :deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}

.admin-users :deep(.el-button) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.admin-users :deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.admin-users :deep(.el-pagination) {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .admin-users {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .admin-users {
    padding: 10px;
  }

  .admin-users :deep(.el-card) {
    margin-bottom: 15px;
  }

  .admin-users :deep(.el-table) {
    font-size: 12px;
  }

  .admin-users :deep(.el-table th),
  .admin-users :deep(.el-table td) {
    padding: 8px 4px;
  }

  .admin-users :deep(.el-pagination) {
    justify-content: center;
    flex-wrap: wrap;
  }
}

@media (max-width: 480px) {
  .admin-users {
    padding: 8px;
  }

  .admin-users :deep(.el-statistic__number) {
    font-size: 20px;
  }
}
</style>

